<?php
/**
 * 获取GET参数
 * @param $a
 * @param mixed $def 如果空则返回此值
 * @return mixed|string
 */
function getGet($a, $def = '')
{
    if (isset($_GET[$a])) {
        return $_GET[$a];
    } else {
        return $def;
    }
}

/**
 * 获取POST参数
 * @param $a
 * @param mixed $def 如果空则返回此值
 * @return mixed|string
 */
function getPost($a, $def = '')
{
    if (isset($_POST[$a])) {
        return $_POST[$a];
    } else {
        return $def;
    }
}

/* * 获取GET或POST参数
 * @param $a
 * @return ''
 */
function getRequest($a, $def = '')
{
    if (isset($_GET[$a])) {
        return $_GET[$a];
    } else if (isset($_POST[$a])) {
        return $_POST[$a];
    } else {
        return $def;
    }
}

/**
 * cookie获取
 * @param $a
 * @param null $def
 * @return mixed|null
 */
function cookie_get($a, $def = '')
{
    if (isset($_COOKIE[$a])) {
        return $_COOKIE[$a];
    } else {
        return $def;
    }
}

/**
 *  设置Cookie
 * @param string $key 键名
 * @param string $val 值
 * @param string $minute 保留时间，分钟
 */
function cookie_set($key, $val, $minute = 60)
{
    if ($minute) {
        setcookie($key, $val, time() + 60 * $minute, '/');
    } else {
        setcookie($key, $val, null, '/');
    }
}

/** 获取Session
 * @param $a
 * @return string| null
 */
function session_get($a, $def = '')
{
    if (!isset($_SESSION)) {
        @session_start();
    }

    if (isset($_SESSION[$a])) {
        return $_SESSION[$a];
    } else {
        return $def;
    }
}

/** 设置Session
 * @param $a Session的名称
 * @param $v
 * @return null
 */
function session_set($a, $v)
{
    if (!isset($_SESSION)) {
        @session_start();
    }

    $_SESSION[$a] = $v;
}

/**
 * 注销当前用户的session
 */
function session_clear()
{
    if (!isset($_SESSION)) {
        @session_start();
    }
    session_destroy();
}

/**
 * 退出,清空session
 */
function session_logout()
{
    setcookie('admin_' . cookiehash, '', time() + 604800, "/");
    setcookie('nick_' . cookiehash, '', time() + 604800, "/");
    if (!empty($value)) {
        $value = md5($value . SiteHash);
    }
    setcookie('psw_' . cookiehash, '', time() + 604800, "/");
    setcookie('token_' . cookiehash, '', time() + 604800, "/");
    if (!isset($_SESSION)) {
        @session_start();
    }
    session_destroy();
    unset($_SESSION);
}


/**
 * 设定session id
 * @param $session
 */
function setSessionID($session)
{
    session_id($session);
}

/**
 * @param string $Origins 允许跨域访问的域名或网址数组，请使用小写字母
 * 如，['baidu.com','www.baidu.com']，
 * 传递*字符串，则表示允许所有来源
 * 空或其他值，则表示不允许跨域
 * @return bool
 */
function allowOrigin($Origins = "*")
{
    if (is_string($Origins) && $Origins == "*") {
        @header("Access-Control-Allow-Origin: *");
    } else if (is_array($Origins) && count($Origins) > 0) {
        $http_referer = get_http_referer();
        if (!in_array($http_referer, $Origins)) {
            return false;
        }
        @header("Access-Control-Allow-Origin:" . "//" . join(",//", $Origins));
    } else {
        return false;
    }

    @header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE, OPTIONS');
    @header('Access-Control-Allow-Headers:*');
    @header('Access-Control-Allow-Credentials: true');
    @header('Content-type: text/html; charset=utf8');
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        @header('Access-Control-Max-Age: 1728000');
        @header('Content-Length:0');
        @header('Content-type: application/json');
        exit("");
    }
    return false;
}

/**
 * 获取来路域名
 * @return mixed
 */
function get_http_referer()
{
    $url = get_referer_url(); //获取完整的来路URL
    $str = strtolower($url);
    $str = str_replace("http://", "", $str); //去掉http://
    $str = str_replace("https://", "", $str); //去掉http://
    $strdomain = explode("/", $str); // 以“/”分开成数组
    $domain = $strdomain[0]; //取第一个“/”以前的字符
    return $domain;
}

//访问来源
function get_referer_url()
{
//    $len = strlen(http_url_path());
    //    $referer2 = substr($referer, $len);
    return getServer('HTTP_REFERER');
}

//网址
function http_url_path()
{
    $port = getServer('SERVER_PORT');
    $host = getServer('HTTP_HOST');
    $https = strtolower(getServer('HTTPS', 'off'));
    $proto = strtolower(getServer('HTTP_X_FORWARDED_PROTO'));
    $path = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
    $http = (($port == 443) || $proto == 'https' || ($https && $https != 'off')) ? 'https' : 'http';
    return "$http://$host$path/";
}


/**
 * 获取请求的URL
 * @return bool|mixed|string
 */
function getRequestUri()
{
    if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
    } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
    } elseif (isset($_SERVER['HTTP_REQUEST_URI'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_REQUEST_URI'];
    }
    if (!UrlRewrite) {
        $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen(SystemDir));
        if (substr($_SERVER['REQUEST_URI'], 0, strlen(IndexFile)) == IndexFile) {
            $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen(IndexFile));
        }
        if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis')) {
            $_SERVER['REQUEST_URI'] = iconv("gb2312", "utf-8//IGNORE", $_SERVER['REQUEST_URI']);
            $_SERVER['REQUEST_URI'] = urlencode($_SERVER['REQUEST_URI']);
            $_SERVER['REQUEST_URI'] = safe_uri_decode($_SERVER['REQUEST_URI']);
        }
    } else {
        if ($_SERVER['REQUEST_URI'] == '/' . IndexFile) {
            $_SERVER['REQUEST_URI'] = '/';
        }
    }
    $uri = $_SERVER['REQUEST_URI'];
    if (substr($uri, 0, 1) != '/') {
        $uri = '/' . $uri;
    }
    return $uri;
}

/**
 * 获取请求方式 get post put delete……
 * @return string
 */
function request_method()
{
    return strtolower($_SERVER['REQUEST_METHOD']);
}

/**
 * 绑定的域名或IP
 * @return string
 */
function server_name()
{
    if (!isset($_SERVER['UUUSERVER_NAME'])) {
        if (isset($_SERVER['HTTP_HOST'])) {
            $thisserver_names = explode(':', $_SERVER['HTTP_HOST']);
            $_SERVER['UUUSERVER_NAME'] = $thisserver_names[0];
        } else {
            $_SERVER['UUUSERVER_NAME'] = $_SERVER['SERVER_NAME'];
        }
        $_SERVER['UUUSERVER_NAME'] = strtolower($_SERVER['UUUSERVER_NAME']);
    }
    return $_SERVER['UUUSERVER_NAME'];
}

/**
 * 绑定的访问端口
 * @return string
 */
function server_port()
{
    if (!isset($_SERVER['UUUSERVER_PORT'])) {
        if (isset($_SERVER['HTTP_HOST'])) {
            $thisserver_port = explode(':', $_SERVER['HTTP_HOST']);
            if (isset($thisserver_port[1])) {
                $_SERVER['UUUSERVER_PORT'] = $thisserver_port[1];
            } else {
                $_SERVER['UUUSERVER_PORT'] = '80';
            }
        } elseif (isset($_SERVER['SERVER_PORT'])) {
            $_SERVER['UUUSERVER_PORT'] = $_SERVER['SERVER_PORT'];
        } else {
            $_SERVER['UUUSERVER_PORT'] = '80';
        }
        if ($_SERVER['UUUSERVER_PORT'] == '80') {
            $_SERVER['UUUSERVER_PORT'] = '';
        } else {
            $_SERVER['UUUSERVER_PORT'] = ':' . $_SERVER['UUUSERVER_PORT'];
        }
    }
    return $_SERVER['UUUSERVER_PORT'];
}

/**
 * 为url自动添加上http://
 * @param string $url
 * @return string $url
 */
function add_http($url)
{
    if (!preg_match("/^(http|https):/i", trim($url))) $url = 'http://' . $url;

    return $url;
}

//将http转换为https开头
function add_https($url)
{
    if (!preg_match("/^(http|https):/i", trim($url))) $url = 'https://' . $url;
    return $url;
}


function ip()
{
    $conf = getServer('conf');
    $ip = '0.0.0.0';
    if (empty($conf['cdn_on'])) {
        $ip = getServer('REMOTE_ADDR');
    } else {
        if (isset($_SERVER['HTTP_CDN_SRC_IP'])) {
            $ip = $_SERVER['HTTP_CDN_SRC_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENTIP'])) {
            $ip = $_SERVER['HTTP_CLIENTIP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            $arr = array_filter(explode(',', $ip));
            $ip = trim(end($arr));
        } else {
            $ip = getServer('REMOTE_ADDR');
        }
    }
    return long2ip(ip2long($ip));
}


function is_robot()
{
    $agent = getServer('HTTP_USER_AGENT');
    $robots = array('bot', 'spider', 'slurp');
    foreach ($robots as $robot) {
        if (strpos($agent, $robot) !== FALSE) {
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * 获取当前顶级域名
 */
function top_domain()
{
    $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']));

    $host = strtolower($host);
    if (strpos($host, '/') !== false) {
        $parse = @parse_url($host);
        $host = $parse['host'];
    }
    $topleveldomaindb = array('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me', 'asia', 'mobi', 'tech', 'wang');
    $str = '';
    foreach ($topleveldomaindb as $v) {
        $str .= ($str ? '|' : '') . $v;
    }
    $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
    if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
        $domain = $matchs['0'];
    } else {
        $domain = $host;
    }
    return $domain;
}


/**
 * 检测是否是Ajax提交
 *
 * @return bool
 */
function is_ajax_request()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(trim($_SERVER['HTTP_X_REQUESTED_WITH'])) == 'xmlhttprequest');
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return true;
    }
    return false;
}

/**
 * 检测是否是本地IP
 */
function is_local_ip()
{
    $serverIP = $_SERVER['SERVER_ADDR'];
    if ($serverIP == '127.0.0.1') return true;
    if (strpos($serverIP, '10.60') !== false) return false;
    return !filter_var($serverIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
